import java.util.Arrays;

public class Solution1031 {
    public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
        int[] sum=new int[nums.length+1];
        for (int i=0;i<nums.length;i++){
            sum[i+1]=sum[i]+nums[i];
        }
        int[] a=new int[nums.length];
        int[] b=new int[nums.length];
        Arrays.fill(a,-1);
        Arrays.fill(b,-1);
        a[firstLen-1]=sum[firstLen];
        for (int i=firstLen;i<nums.length;i++){
            a[i]=Math.max(a[i-1],sum[i+1]-sum[i-firstLen+1]);
        }
        b[nums.length-firstLen]=sum[nums.length]-sum[nums.length-firstLen];
        for (int i=nums.length-firstLen-1;i>=0;i--){
            b[i]=Math.max(b[i+1],sum[i+firstLen]-sum[i]);
        }
        int[] c=new int[nums.length];
        int[] d=new int[nums.length];
        Arrays.fill(c,-1);
        Arrays.fill(d,-1);
        c[secondLen-1]=sum[secondLen];
        for (int i=secondLen;i<nums.length;i++){
            c[i]=Math.max(c[i-1],sum[i+1]-sum[i-secondLen+1]);
        }
        d[nums.length-secondLen]=sum[nums.length]-sum[nums.length-secondLen];
        for (int i=nums.length-secondLen-1;i>=0;i--){
            d[i]=Math.max(d[i+1],sum[i+secondLen]-sum[i]);
        }
        int max=Integer.MIN_VALUE;
        for (int i=0;i<nums.length-1;i++){
            if (a[i]>=0 && d[i+1]>=0){
                max=Math.max(max,a[i]+d[i+1]);
            }
            if (c[i]>=0 && b[i+1]>=0){
                max=Math.max(max,c[i]+b[i+1]);
            }
        }
        return max;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1031().maxSumTwoNoOverlap(new int[]{0,6,5,2,2,5,1,9,4},1,2));
    }
}
